package com.tailyou.hms.neteasecloudmusic;

import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Timer;
import java.util.TimerTask;

public class MusicPlayActivity extends AppCompatActivity {

    private MusicBean musicBean;
    private TextView tvMusicName, tvDesc;
    private ImageView ivPlayOrPause, ivPreMusic, ivNextMusic, ivMusicPic;
    private PlayService.MusicBinder musicBinder;
    private boolean isPlaying;
    private ObjectAnimator objectAnimator;
    private Timer mTimer;
    private SeekBar msb;
    private TextView tvTimeAll, tvTimePlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_play);
        bindService();
        musicBean = (MusicBean) getIntent().getExtras().get("MusicBean");
        updateUI();
        ivPlayOrPause = findViewById(R.id.ivPlayOrPause);
        ivPreMusic = findViewById(R.id.ivPreMusic);
        ivNextMusic = findViewById(R.id.ivNextMusic);
        ivMusicPic = findViewById(R.id.music_pic);
        msb = findViewById(R.id.msb);
        ivPreMusic.setOnClickListener(v -> lastMusic());
        ivNextMusic.setOnClickListener(v -> nextMusic());
        //监听SeekBar进度变化
        msb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //如果时人为手动拖拽改变进度，则通知音乐播放服务更改播放进度
                if (fromUser) {
                    musicBinder.setPosition(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //暂时不用，开始拖拽时回调
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //暂时不用，结束拖拽时回调
            }
        });
        tvTimePlay = findViewById(R.id.tv_play_prg);
        tvTimeAll = findViewById(R.id.tv_music_time);
        ivPlayOrPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPlaying) {
                    doPause();
                } else {
                    doPlay();
                }
            }
        });
        initAnimation();
        initTimer();
    }

    /**
     * 下一曲
     */
    private void nextMusic() {
        //下一曲，实现歌单循环
        int index = musicBean.getSqe() + 1;
        index %= LovedMusicActivity.listData.size();
        musicBean = LovedMusicActivity.listData.get(index);
        //切换音乐，之前的播放进度清零
        musicBinder.setPosition(0);
        updateUI();
        doPlay();
    }

    /**
     * 上一曲
     */
    private void lastMusic() {
        //上一曲，实现歌单循环
        int index = musicBean.getSqe() - 1;
        if (index < 0) index += LovedMusicActivity.listData.size();
        musicBean = LovedMusicActivity.listData.get(index);
        //切换音乐，之前的播放进度清零
        musicBinder.setPosition(0);
        updateUI();
        doPlay();
    }

    /**
     * 更新显示的歌名和描述
     */
    private void updateUI() {
        Log.d("MusicBean", musicBean.toString());
        tvMusicName = findViewById(R.id.tvMusicName);
        tvDesc = findViewById(R.id.tvDesc);
        tvMusicName.setText(musicBean.getMusicName());
        tvDesc.setText(musicBean.getDesc());
    }

    /**
     * 初始化定时器任务，每秒更新一下播放进度
     */
    private void initTimer() {
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        updateMusicTime();
                    }
                });
            }
        }, 1000, 1000);
    }

    /**
     * 更新时间，包括歌曲总时长和当前播放进度
     */
    private void updateMusicTime() {
        long duration = musicBinder.getMusicDuration();
        msb.setMax((int) duration);
        tvTimeAll.setText(String.format("%02d:%02d", duration / 1000 / 60, duration / 1000 % 60));
        long position = musicBinder.getPosition();
        msb.setProgress((int) position);
        tvTimePlay.setText(String.format("%02d:%02d", position / 1000 / 60, position / 1000 % 60));
        if (position / 1000 == duration / 1000) {
            //播放完成，切回暂停
            nextMusic();
        }
    }

    /**
     * 初始化碟片的旋转动画
     */
    private void initAnimation() {
        objectAnimator = ObjectAnimator.ofFloat(ivMusicPic, "rotation", 0f, 360f);
        objectAnimator.setDuration(24000);// 持续24秒
        LinearInterpolator mLinearInterpolator = new LinearInterpolator();
        objectAnimator.setInterpolator(mLinearInterpolator);// 设置动画匀速
        objectAnimator.setRepeatCount(ObjectAnimator.INFINITE);// 无限播放
        objectAnimator.setRepeatMode(ObjectAnimator.RESTART);// 重复播放模式
    }

    /**
     * 开始播放
     */
    private void doPlay() {
        isPlaying = true;
        ivPlayOrPause.setImageResource(R.mipmap.play_btn_pause_prs);
        objectAnimator.start();
        if (musicBinder.getPosition() == 0) {
            musicBinder.play(musicBean.getResId());
        } else {
            musicBinder.replay();
        }
    }

    /**
     * 暂停播放
     */
    private void doPause() {
        isPlaying = false;
        ivPlayOrPause.setImageResource(R.mipmap.play_btn_play);
        objectAnimator.pause();
        musicBinder.pause();
    }

    /**
     * 绑定PlayService
     */
    private void bindService() {
        bindService(new Intent(MusicPlayActivity.this, PlayService.class),
                new ServiceConnection() {
                    @Override
                    public void onServiceConnected(ComponentName name, IBinder service) {
                        musicBinder = (PlayService.MusicBinder) service;
                        if (musicBinder.isPlaying()) {
                            doPlay();
                            updateMusicTime();
                        }
                    }

                    @Override
                    public void onServiceDisconnected(ComponentName name) {
                        musicBinder.close();
                    }
                }, BIND_AUTO_CREATE);
    }

}